<?php

/*
 *Copyright (C), WhiteBlue
 *File name: controller.php
 *Author: Version: 2015.3.9
 *Description: 控制器实现
 */

namespace core\main;

abstract class controller
{
    protected $params;
    protected $method;
    protected $view;
    protected $data;
    protected $errorPage;

    public function render($viewName = null)
    {
        if (!$viewName) {
            throw new InvalidArgumentException("视图名称不能为空！");
        } else {
            $viewFilePath = self::getFilePath($viewName);
            if (is_file($viewFilePath)) {
                if (!empty($this->data)) {
                    extract($this->data);
                }
                require($viewFilePath);
            } else {
                throw new UnexpectedValueException($viewFilePath . "视图文件不存在！");
            }
        }
    }

    public function setAttr($key, $value = null)
    {
        $this->data[$key] = $value;
        return $this;
    }

    private static function getFilePath($viewName)
    {
        $filePath = str_replace('.', '/', $viewName);
        return VIEW_PATH . $filePath . '.php';
    }


    public abstract function index();

    public function setParams($params)
    {
        $this->params = $params;
    }

    public function setMethod($method)
    {
        $this->method = $method;
    }

    public function getMethod()
    {
        return $this->method;
    }

    public function getParam($num, $default=null)
    {
        if (isset($this->params[$num])) {
            return htmlspecialchars($this->params[$num]);
        } else {
            return $default;
        }
    }

    public function redirect_local($url)
    {
        header('location:http://' . URL_BASE . '?' . $url);
    }

    public function redirect($url){
        header('location:http://'.$url);
    }


    public function renderError($error='ERROR 404')
    {
        if(isset($this->errorPage)){
            $this->setAttr('error',$error);
            $this->render($this->errorPage);
        }
    }


}